package com.yixing.tech.entity.entity.attr;

import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.base.CustomAggregationOperation;
import com.yixing.tech.common.enums.YesOrNo;
import com.yixing.tech.entity.entity.RequestType;
import com.yixing.tech.common.vo.s5.EntitySchema;
import com.yixing.tech.entity.service.EntityBaseService;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author yixing tech
 * at 2021/10/9
 * describe：
 */
public class DictArray extends AttrType {
    public DictArray() {
        super("字典数组", "dictArray");
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr) throws BusinessException {
        super.out(operations, attr);
        String relationalF = attr.getRelationalField();
        String sql = "{ $lookup:{ " +
                "from:'dict'," +
                "let:{ location_id:'$" + attr.getCode() + "'}," +
                "pipeline:[" +
                "{$match:" +
                "{'$and':[" +
                "{$expr:{" +
                "$in:['$" + (ObjectUtils.isEmpty(relationalF) ? "_id" : relationalF) + "',{$ifNull :['$$location_id',[]]}]" +
                "}" +
                "}" +
                ",{'parentId':'" + attr.getReference() + "'}" +
                "]" +
                "}" +
                "}," +
                "{$project:{name:1,value:1}}" +
                "]," +
                "as:'" + attr.getCode() + "'}}";
        operations.add(new CustomAggregationOperation(sql));
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr, RequestType requestType) throws BusinessException {
        out(operations, attr);
    }

    @Override
    public Object wrapValue(EntitySchema.AttrVO attr, Object value, MongoTemplate mongoTemplate, EntityBaseService objService, String tenantId) throws BusinessException {
        if (ObjectUtils.isEmpty(value)) {
            return value;
        }
        String[] values = value.toString().trim().split(",");
        Object reference = attr.getReference();
        // 字典应用
        String dictParentId = reference instanceof List ? ((List) reference).get(0).toString() : reference.toString();
        if (ObjectUtils.isEmpty(dictParentId)) {
            throw new BusinessException("未配置字典");
        }
        List<Document> dicts = mongoTemplate.find(Query.query(Criteria.where("isDelete").ne(YesOrNo.YES.ordinal())
                .and("name").in(values).and("parentId").is(dictParentId)), Document.class, "dict");
        return dicts;
    }
}
